package com.zzyl.service.impl;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {

    //属性注入
    @Value("${zzyl.wechat.AppID}")
    private String AppID;
    @Value("${zzyl.wechat.AppSecret}")
    private String AppSecret;



    /**
     * 获取用户的openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        String AppID = "wxbf42e031456430d9";
        String AppSecret = "cd4a063babcf7f09f3552b2fd54638e5";
        String grantType = "authorization_code";
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid",AppID);
        map.put("secret",AppSecret);
        map.put("js_code",code);
        map.put("grant_type",grantType);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HttpResponse execute = HttpUtil.createRequest(Method.GET, url).form(map).execute();
        String body = execute.body();
        JSONObject entries = JSONUtil.parseObj(body);
        return entries.getStr("openid");
    }

    /**
     * 请求获取用户的手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhoneNumber(String code) {//手机号的获取凭证
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        HttpResponse execute = HttpUtil.createRequest(Method.POST, url).body(JSONUtil.toJsonStr(map)).execute();
        String json = execute.body();
        JSONObject jsonObject = JSONUtil.parseObj(json);
        String phone_info = jsonObject.getStr("phone_info");
        JSONObject entries = JSONUtil.parseObj(phone_info);
        return entries.getStr("phoneNumber");
    }


    private  String getAccessToken(){
        String grantType = "client_credential";
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, Object> secretMap = getSecretMap();
        secretMap.put("grant_type",grantType);
        HttpResponse execute = HttpUtil.createRequest(Method.GET, url).form(secretMap).execute();
        String body = execute.body();
        JSONObject josn = JSONUtil.parseObj(body);
        return  josn.getStr("access_token");
    }


    /**
     * 统一处理秘钥Map
     * @return
     */
    private Map<String,Object> getSecretMap(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid",AppID);
        map.put("secret",AppSecret);
        return map;
    }
}
